package com.swallow.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swallow.common.exception.CloudDemoException;
import com.swallow.common.result.ResultCodeEnum;
import com.swallow.common.utils.AuthContextHolder;
import com.swallow.user.entity.User;
import com.swallow.user.entity.dto.UserDto;
import com.swallow.user.mapper.UserMapper;
import com.swallow.user.service.UserService;
import com.swallow.user.tool.PasswordUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;

/**
 * @program:cloud_demo
 * @author: 马雨清
 * @Time: 2025/4/20  1:03
 * @description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean register(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        String password = PasswordUtil.hashPassword(user.getPassword());
        user.setCreateTime(new Date());
        user.setStatus(1);
        user.setPassword(password);
        boolean result = save(user);
        return result;
    }

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Long login(HashMap<String, String> map) {
        String username = map.get("username");
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        User user = new User();
        user.setUsername(username);
        user = userMapper.selectOne(userLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(user)){
            throw new CloudDemoException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        String password = PasswordUtil.hashPassword(map.get("password"));
        if (!StringUtils.pathEquals(user.getPassword(),password)){
            throw new CloudDemoException(ResultCodeEnum.PASSWORD_ERROR);
        }
        AuthContextHolder.setUserId(user.getUserId());
        redisTemplate.opsForValue().set("userid",user.getUserId());
        return user.getUserId();
    }
}
